package cn.gailvlun.gll.presentation.chat

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.SelectHolder
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.chatlib.message.Message
import cn.gailvlun.gll.chatlib.message.MessageType
import cn.gailvlun.gll.databinding.ItemCreateGroupBinding
import cn.gailvlun.gll.net.*
import cn.gailvlun.gll.net.apartment.room.GetRoomDetailRes
import cn.gailvlun.gll.net.apartment.room.Room
import cn.gailvlun.gll.net.base.Profile
import cn.gailvlun.gll.net.group.CreateGroupReq
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.chat.adapter.CreateGroupAdapter
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.join
import cn.gailvlun.gll.widget.CommonItemDecoration
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_create_group.*

class CreateGroupActivity: BaseActivity(), OnLoadmoreListener {

    companion object {
        fun openActivity(context: Context) {
            context.apply {
                startActivity(Intent(this, CreateGroupActivity::class.java))
            }
        }
    }

    private var mAdapter : CreateGroupAdapter? = null
    private var mLayoutManager: LinearLayoutManager? = null

    private var mQueryParam = QueryParam()

    override fun initComponent() {
        setContentView(R.layout.activity_create_group)

        mAdapter = CreateGroupAdapter(mContext)
        recycler_view.adapter = mAdapter
        mAdapter?.setDecorator { holder, _, _ ->
            (holder.binding as ItemCreateGroupBinding).apply {
                this.root.setOnClickListener {
                    item?.selected = !item?.selected!!
                    holder.binding.invalidateAll()

                    invalidateMenu()
                }
            }
        }

        mLayoutManager = LinearLayoutManager(mContext)
        recycler_view.layoutManager = mLayoutManager

        srl.setOnLoadmoreListener(this)
        srl.isEnableRefresh = false

        recycler_view.addItemDecoration(CommonItemDecoration(73, 0, 1, resources.getColor(R.color.line_color), Color.WHITE))

        invalidateMenu()
    }

    private fun invalidateMenu() {
        
        val selectedCount = mAdapter?.getHowManySelected()
        if (selectedCount!! < 2) {
            nbv.setMenuEnable(false)
            nbv.setMenuText("确认")
        } else {
            nbv.setMenuEnable(true)
            nbv.setMenuText("确认($selectedCount)")
        }
    }

    override fun createHandler() {
        nbv.setOnBackListener {
            onBackPressed()
        }

        nbv.setOnMenuClickListener {
            val pd = DialogUtil.showIndeterminate(mContext)
            HttpMethods.getGroupService()
                    .createGroup(CreateGroupReq().apply {
                        user_list = mAdapter?.getSelectedList()?.map {
                            it.data.id
                        }
                    })
                    .compose(RxUtil.applyScheduler())
                    .compose(bindToLifecycle())
                    .subscribe(object: HttpSubscriber<Room>() {
                        override fun onSuccess(response: Room) {
                            getMemberList(response)
                        }

                        override fun onFailure(errMsg: String?, response: Room?, code: Int) {
                            DialogUtil.showError(mContext, errMsg)
                        }

                        override fun onFinish() {
                            super.onFinish()
                            pd.dismiss()
                        }

                    })
        }
    }

    fun getMemberList(room: Room) {
        HttpMethods.getGroupService()
                .getGroupMember(room.id)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object: HttpSubscriber<ListRes<Member>>() {
                    override fun onSuccess(response: ListRes<Member>) {
                        room.name = join("、", response.results, true)
                        
                        val sb = StringBuilder().append(room.owner.name)
                                .append("邀请\"")
                                .append(join("、", response.results, false))
                                .append("\"加入了群聊")
                        val msg = Message()
                        msg.type = MessageType.initInfo
                        msg.text = sb.toString()
                        msg.created = room.created

                        msg.dialogId = "room:" + room.id

                        getMyMember(room, msg)
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<Member>?, code: Int) {

                    }
                })
    }

    fun getMyMember(room: Room, msg: Message) {
        HttpMethods.getRoomService().getRoomDetail(room.id)
                .compose(bindToLifecycle())
                .compose(RxUtil.applyScheduler())
                .subscribe(object: HttpSubscriber<GetRoomDetailRes>() {
                    override fun onSuccess(response: GetRoomDetailRes) {
                        val realm = Realm.getInstance(ChatDB2.getConfiguration())
                        realm.executeTransaction {
                            it.insertOrUpdate(room)
                            it.insertOrUpdate(response.member)
                            it.insertOrUpdate(msg)
                        }
                        realm.close()

                        ChatActivity.openActivity(mContext, "room:${response.room.id}")
                        finish()
                    }

                    override fun onFailure(errMsg: String?, response: GetRoomDetailRes?, code: Int) {

                    }

                })
    }

    override fun loadData(savedInstanceState: Bundle?) {
        mQueryParam.resetPage()
        HttpMethods.getFriendService()
                .getFriends(mQueryParam.page)
                .compose(bindToLifecycle())
                .compose(RxUtil.applyScheduler())
                .subscribe(object: HttpSubscriber<ListRes<Profile>>() {
                    override fun onSuccess(response: ListRes<Profile>) {
                        mAdapter?.set(SelectHolder.transform(response.results))
                        srl.isEnableLoadmore = response.isNext
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<Profile>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }

    override fun onLoadmore(refreshlayout: RefreshLayout?) {
        mQueryParam.nextPage()
        HttpMethods.getFriendService()
                .getFriends(mQueryParam.page)
                .compose(bindToLifecycle())
                .compose(RxUtil.applyScheduler())
                .subscribe(object: HttpSubscriber<ListRes<Profile>>() {
                    override fun onSuccess(response: ListRes<Profile>) {
                        mAdapter?.addAll(SelectHolder.transform(response.results))
                        srl.isEnableLoadmore = response.isNext
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<Profile>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        srl.finishLoadmore()
                    }
                })
    }

    object Util {
        @JvmStatic
        fun getGaiId(item: Profile) : String {
            return "概率论ID：${item.gaiid}"
        }
    }

}